# Uncomment this if you reference any of your controllers in activate
# require_dependency "application_controller"

require "radiant-flapper-extension/version"

class FlapperExtension < Radiant::Extension
  version RadiantFlapperExtension::VERSION
  description "Push new tweets as you publish pages"
  url "https://github.com/johnmuhl/flapper"

  extension_config do |config|
    config.after_initialize do
      if ["flapper.username", "flapper.domain", "flapper.consumer_key",
          "flapper.consumer_secret", "flapper.oauth_token",
          "flapper.oauth_token_secret"].any? { |key| Radiant::Config[key].blank? }
        puts "!! Flapper is not configured. https://github.com/johnmuhl/flapper"
      end
    end
  end

  def activate
    Page.class_eval do
      require "googl"
      require "twitter"
      after_save :notify_twitter
      def notify_twitter
        if parent
          if notifiable?
            content = self.field("Tweet")["content"]
            if content.blank?
              logger.error "!! Tweet field does not have any content."
            else
              url = shorten "http://#{Radiant::Config["flapper.domain"]}/#{parent.slug}/#{self.slug}/"
              message = content[0..(136 - url.length)] + "..." + url
              begin
                Twitter.configure do |config|
                  config.consumer_key = Radiant::Config['flapper.consumer_key']
                  config.consumer_secret = Radiant::Config['flapper.consumer_secret']
                  config.oauth_token = Radiant::Config['flapper.oauth_token']
                  config.oauth_token_secret = Radiant::Config['flapper.oauth_token_secret']
                end
                status = Twitter::Client.new.update(message)
                self.class.update_all({ :twitter_id => status.id }, :id => self.id)
              rescue Exception
                logger.error "!! Invalid Twitter configuration."
              end
            end
          end
        end
      end
      def twitter_configured?
        !["flapper.username", "flapper.domain", "flapper.consumer_key",
          "flapper.consumer_secret", "flapper.oauth_token", "flapper.oauth_token_secret"
         ].any? { |key| Radiant::Config[key].blank? }
      end
      def notifiable?
        published? &&
        twitter_configured? &&
        parent.notify_twitter_of_children? &&
        !self.twitter_id
      end
      def shorten url
        if google_configured?
          googl = Googl.client(Radiant::Config["flapper.google_email"], Radiant::Config["flapper.google_password"])
        else
          googl = Googl
        end
        googl.shorten(url).short_url
      end
      def google_configured?
        !["flapper.google_email", "flapper.google_password"
         ].any? { |key| Radiant::Config[key].blank? }
      end
    end
    admin.pages.edit.add :extended_metadata, "flapper"
  end

end
